<template>
  <div class="reg">
    <logo></logo>
    <van-form @submit="onSubmit">
      <van-field
        v-model="username"
        name="userName"
        label="用户名"
        placeholder="用户名"
        :rules="[{ required: true, message: '请填写用户名' }]"
      />
      <van-field
        v-model="password"
        type="password"
        name="password"
        label="密码"
        placeholder="密码"
        :rules="[{ required: true, message: '请填写密码' }]"
      />
      <van-field
        v-model="repassword"
        type="password"
        name="repwd"
        label="密码"
        placeholder="请确认密码"
        :rules="[{ required: true, message: '请再次填写密码' }]"
      />
      <div style="margin: 16px">
        <van-button round block type="info" native-type="submit">提交</van-button>
      </div>
    </van-form>
    <router-link :to="{ name: 'login' }">已有账号，我要登录</router-link>
  </div>
</template>

<script>
import { Toast } from 'vant';
import Logo from '../components/Logo.vue';
import { regAPI } from '../services/auth';
import { setToken } from '../utils/tools';

export default {
  data() {
    return {
      username: '',
      password: '',
      repassword: '',
    };
  },
  components: {
    Logo,
  },
  methods: {
    async onSubmit(values) {
      if (this.password === this.repassword) {
        // console.log('submit', values);
        const res = await regAPI(values);
        // console.log(res);
        if (res.code === 1) {
          Toast.success('注册成功');
          setToken(res.data);
          this.$router.replace({
            name: 'User',
          });
        } else {
          Toast.fail(res.data);
        }
      } else {
        Toast.fail('两次输入的密码不一致');
      }
    },
  },
};
</script>

<style>
.reg {
  padding: 20px 0;
}
</style>
